﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WMS.FC.Domain.DomainObject.System;
using WMS.FC.Domain.Repository;
using WMS.FC.Domain.Service.Equipment.Interface;
using WMS.FC.Domain.Service.System;

namespace WMS.FC.Domain.Service.Equipment
{
    public class ChangeEquipmentStateService : ServiceBase, IChangeEquipmentStateService
    {
        protected readonly IEquipmentRepository equipmentRepository;

        public ChangeEquipmentStateService(
            ILogger<ServiceBase> logger,
            IOptions<WmsSettings> options,
            IMapper mapper,
            IEquipmentRepository equipmentRepository)
            : base(logger, options, mapper)
        {
            this.equipmentRepository = equipmentRepository;
        }

        public async Task<ActionResultBase> ChangeEquipmentState(string? equipmentCode, string? wcsState, UserInfo userInfo)
        {
            var result = new ActionResultBase("变更设备状态");
            try
            {
                if (string.IsNullOrWhiteSpace(equipmentCode))
                    return result.ArgumentError("设备编码不能为空");

                if (string.IsNullOrWhiteSpace(wcsState))
                    return result.ArgumentError("设备状态不能为空");

                var stateCode = "EquipmentState_OK";
                switch (wcsState)
                {
                    case "0":
                        stateCode = "EquipmentState_Init";
                        break;
                    case "1":
                        stateCode = "EquipmentState_OK";
                        break;
                    case "2":
                        stateCode = "EquipmentState_Manual";
                        break;
                    case "3":
                        stateCode = "EquipmentState_Error";
                        break;
                    case "4":
                        stateCode = "EquipmentState_Auto";
                        break;
                }

                var equipmentPO = await equipmentRepository.GetEquipment(options.Value.LineCode, equipmentCode);
                if (equipmentPO == null)
                    return result.BusinessError($"设备编码:{equipmentCode},设备数据未找到");

                equipmentPO.StateCode = stateCode;
                var count = await equipmentRepository.Update(equipmentPO, userInfo);
                if (count == 0)
                    return result.DbError("更新设备状态异常");
            }
            catch (Exception ex)
            {
                return result.Exception(ex);
            }

            return result;
        }
    }
}
